//
//  ByBigImageViewController.m
//  beibei_ios
//
//  Created by mc on 16/5/16.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByBigImageViewController.h"

@interface ByBigImageViewController ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate>{
    
    UICollectionView *_bigImageCollection;
    UIPageControl *_pageControl;
}

@end

@implementation ByBigImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = @"图片浏览";
    
    [self _createViews];
    [self createLeftBackBarButtonItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenAction:) name:@"hidden" object:nil];
    // Do any additional setup after loading the view.
}

- (void)dealloc {
    // 移除相应的通知
    // 如果通知不移除 容易造成程序崩溃
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)hiddenAction:(NSNotification *)notification {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)viewDidAppear:(BOOL)animated {
    // 滑动到点击的那个单元格
    [_bigImageCollection scrollToItemAtIndexPath:_indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    // 第一个单元格显示的图片 还原成第一张图片
    _indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
}


- (void)_createViews {
    
    // 创建布局对象
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    // 设置单元格大小
    flow.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    // 设置单元格的水平间隙
    flow.minimumInteritemSpacing = 10;
    // 设置四周间隙
    flow.sectionInset = UIEdgeInsetsMake(0, 0, 0, 10);
    
    // 设置滑动方向
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    // 创建Collection
    _bigImageCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH + 10, SCREEN_HEIGHT) collectionViewLayout:flow];
    _bigImageCollection.backgroundColor = [UIColor blackColor];
    
    // 隐藏滑块
    _bigImageCollection.showsHorizontalScrollIndicator = NO;
    
    // 开启分页效果
    _bigImageCollection.pagingEnabled = YES;
    
    // 设置代理和数据源方法
    _bigImageCollection.dataSource = self;
    _bigImageCollection.delegate = self;
    
    // 注册单元格
    [_bigImageCollection registerClass:[BigImageCell class] forCellWithReuseIdentifier:@"imageCell"];
    
    [self.view addSubview:_bigImageCollection];
    
    
    // 分页视图
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.numberOfPages = _imageData.count;
    _pageControl.currentPage = _indexPath.row;
    [self.view insertSubview:_pageControl aboveSubview:_bigImageCollection];
    _pageControl.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT - 30);
    
}


#pragma mark 数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imageData.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BigImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];
    //加载网络图片
    if (self.isLocal) {
        
        UIImage *image;
        if (indexPath.row == 0) {
            image = _imageData[_indexPath.row];
        }
        else {
            image = _imageData[indexPath.row];
        }
        // 给cell设置图片
        [cell setImage:image];

    }else{
        // 创建一个图片视图
        NSURL *url;
        if (indexPath.row == 0) {
            url = _imageData[_indexPath.row];
        }
        else {
            url = _imageData[indexPath.row];
        }
        // 给cell设置图片的URL
      [cell setImageURL:url];

    }
       return cell;
    
}

#pragma mark - 滑动停止，修改页码
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    
    CGFloat offset = targetContentOffset->x;
    NSInteger page = offset / scrollView.width;
    
    _pageControl.currentPage = page;
}

#pragma mark - 隐藏导航栏
- (void)hiddenNaviBar
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}
#pragma mark - 某个单元格滑出屏幕时调用
// 单元格已经结束显示
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    BigImageCell *disPlayCell = (BigImageCell *)cell;
    // 将滑动视图缩放笔比例还原
    [disPlayCell backScrollView];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



#pragma mark BigImageCell  创建方法

@interface BigImageCell () <UIScrollViewDelegate>
{
    UIImageView *_imageView;
    
    NSTimer *_timer;
    
    BOOL _isBig;     // 控制双击变大恢复
    BOOL _isHidden;  // 控制单击隐藏导航栏
        
}

@property (nonatomic, strong) UIActivityIndicatorView *act;

@end

@implementation BigImageCell

- (void)awakeFromNib {
    // Initialization code
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        [self _createScrollView];
        
        [self _addTap];
    }
    
    return self;
}


- (void)_createScrollView {
    // 创建滑动视图
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.contentView.bounds];
    scrollView.tag = 888;
    [self.contentView addSubview:scrollView];
    
    _imageView = [[UIImageView alloc] initWithFrame:scrollView.bounds];
    _imageView.backgroundColor = [UIColor clearColor];
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    [scrollView addSubview:_imageView];
    
    // 设置滑动视图的代理对象
    scrollView.delegate = self;
    // 设置缩放倍数
    scrollView.minimumZoomScale = 0.3;
    scrollView.maximumZoomScale = 3;
    
    
}


- (void)_addTap {
    
    // 点击的手势识别器
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] init];
    // 点击次数
    tap1.numberOfTapsRequired = 1;
    // 点击的手指数量
    tap1.numberOfTouchesRequired = 1;
    // 添加一个执行的方法
    [tap1 addTarget:self action:@selector(tapAction:)];
    [self addGestureRecognizer:tap1];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] init];
    // 点击次数
    tap2.numberOfTapsRequired = 2;
    // 点击的手指数量
    tap2.numberOfTouchesRequired = 1;
    // 添加一个执行的方法
    [tap2 addTarget:self action:@selector(tapAction:)];
    [self addGestureRecognizer:tap2];
    
    // 设置缩放和隐藏的初始值
    _isBig = NO;
    _isHidden = NO;
    
    // 长按保存
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(savePhoto:)];
    [self addGestureRecognizer:longPress];
    
}

- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    if (tap.numberOfTapsRequired == 2) {
        
        // 双击
        // 如果触发双击 则停止 单击的定时器
        [_timer invalidate];
        
        UIScrollView *scroll = (UIScrollView *)[self.contentView viewWithTag:888];
        // 先判断是否手动放大 如果是 双击操作恢复
        if (scroll.zoomScale != 1) {
            [scroll setZoomScale:1 animated:YES];
            _isBig = NO;
        }
        // 如果是原图则根据_isBig 来判断要放大和还是缩小
        else {
            // 改变的滑动视图的缩放比例
            if (!_isBig) {
                [scroll setZoomScale:3 animated:YES];
            }
            else {
                [scroll setZoomScale:1 animated:YES];
            }
            _isBig = !_isBig;
        }
    }
    else if (tap.numberOfTapsRequired == 1) {
        // 单击
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(tapOneAction) userInfo:nil repeats:NO];
    }
    
}
/**
 *  单击双击的区分
 *
 *  1.触发单击事件 使用一个定时器来判断 延迟0.25秒
 *  2.如果时间到了 但是没有触发双击事件 则执行单击的方法
 *  3.如果触发了双击事件 那就取消定时器
 *
 */
- (void)tapOneAction {
    
    // 单击的时候发送一个通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hidden" object:nil];
    
}

// 设置缩放的视图
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    return _imageView;
}

// 还原缩放视图
- (void)setImageURL:(NSURL *)url {
    
    if (!_act) {
        _act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        _act.hidesWhenStopped = YES;
        _act.center = CGPointMake(self.width / 2, self.height / 2);
        [self.contentView addSubview:_act];
        [_act startAnimating];
    }
    
    __weak typeof(_imageView) w_imgView = _imageView;
    __weak typeof(self) w_self = self;
    [_imageView setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        if (error) {
            w_imgView.image = DEFAULT_IMAGE;
        }
        [w_self.act stopAnimating];
        w_self.act = nil;
    }];
}


- (void)setImage:(UIImage *)image{
    _imageView.image = image;
}




- (void)backScrollView {
    UIScrollView *scroll = (UIScrollView *)[self.contentView viewWithTag:888];
    // 改变的滑动视图的缩放比例
    [scroll setZoomScale:1 animated:NO];
    
}

#pragma mark - 保存事件
- (void)savePhoto:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        
        [UIAlertView showWithTitle:@"提示"
                           message:@"是否保存图片"
                 cancelButtonTitle:@"否"
                 otherButtonTitles:@[@"是"]
                          tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                              
                              if (buttonIndex == 1) {
                                  UIImage *image = _imageView.image;
                                  UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
                              }

                          }];
    }
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    [ByCoreToolAlert alertSuccess:@"保存成功"];
}

@end









